using UnityEngine;
using System.Collections;

public class LevelStatus : MonoBehaviour
{
	//Master Level State Machine Script
	
	public GameObject exitGateway;
	public GameObject levelGoal;
	public AudioClip unlockedSound;
	public AudioClip levelCompleteSound;
	public GameObject mainCamera;
	public GameObject unlockedCamera;
	public GameObject levelCompletedCamera;
	
	/// <summary>
	// Number of items needed to complete the level 
	/// </summary>
	public int itemsNeeded = 0;
	
	private GameObject playerLink;
	
	//Awake() Called by Unity when the script has loaded
	//Initializes the link to the player GameObject
	public void Awake()
	{
		levelGoal.GetComponent<MeshCollider>().isTrigger = false;
		playerLink = GameObject.Find("Player");
		if(!playerLink)
		{
			Debug.LogError("Could not link to Player");	
		}
		//
		levelGoal.GetComponent<MeshCollider>().isTrigger = false;
		
	}
	
	public IEnumerator UnlockLevelExit()
	{
		mainCamera.GetComponent<AudioListener>().enabled = false;
		unlockedCamera.active = true;
		unlockedCamera.GetComponent<AudioListener>().enabled = false;
		exitGateway.GetComponent<AudioSource>().Stop();
		
		if(unlockedSound)
		{
			AudioSource.PlayClipAtPoint(unlockedSound, unlockedCamera.GetComponent<Transform>().position, 2.0f);
			
		}
		
		yield return new WaitForSeconds(1.0f);
		//Energy Web fails briefly
		exitGateway.active = false;
		yield return new WaitForSeconds(0.2f);
		exitGateway.active = true;
		yield return new WaitForSeconds(0.2f);
		exitGateway.active = false;
		levelGoal.GetComponent<MeshCollider>().isTrigger = true;
		yield return new WaitForSeconds(4.0f);
		
		//Switch cameras back
			unlockedCamera.active = false;
			unlockedCamera.GetComponent<AudioListener>().enabled = false;
			mainCamera.GetComponent<AudioListener>().enabled = true;
	}
	
	public IEnumerator LevelCompleted()	
	{
		mainCamera.GetComponent<AudioListener>().enabled = false;
		levelCompletedCamera.active = true;
		levelCompletedCamera.GetComponent<AudioListener>().enabled = true;
		playerLink.GetComponent<ThirdPersonController>().SendMessage("HidePlayer");
		playerLink.transform.position += new Vector3(0, 1, 0) * 500;
		
		if(levelCompleteSound)
		{
			AudioSource.PlayClipAtPoint(levelCompleteSound, levelGoal.transform.position, 2.0f);
		}
		
		levelGoal.animation.Play();
		yield return new WaitForSeconds(levelGoal.animation.clip.length);
		//Show game over sequence
		Application.LoadLevel("Game Over");
		
	}
}


